package com.cityeye.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.cityeye.MMSSessionFactory;
import com.cityeye.mmsentity.MsgInbox;

public class MMSDao {
	public SessionFactory getSF() {
		return MMSSessionFactory.getSessionFactory();
	}

	public List<MsgInbox> getNewMessages() {
		List<MsgInbox> result = new ArrayList<MsgInbox>();
		Session session = null;
		try {
			session = getSF().openSession();
			session.beginTransaction();
			result = session.createCriteria(MsgInbox.class)
					// .add(Restrictions.eq("msgType", MsgInbox.TYPE_MMS))
					.add(Restrictions.eq("mmsdownloadedState",
							MsgInbox.DOWN_STAT_READY)).list();
			session.getTransaction().commit();
		} finally {
			session.close();
		}
		return result;
	}

	public void deleteMessages(List<MsgInbox> msgs) {
		if (msgs == null || msgs.size() < 1)
			return;

		// StringBuffer sb = new StringBuffer("");
		// for(MsgInbox msg:msgs){
		// sb.append(msg.getId());
		// sb.append(",");
		// }
		// String idStr = sb.toString();
		// idStr = idStr.substring(0,idStr.length()-1);

		// getSF().getCurrentSession().beginTransaction();
		// getSF().getCurrentSession().delete("from MsgInbox c where c.id in ("+idStr+")");
		// org.hibernate.Query query =
		// getSF().getCurrentSession().createSQLQuery(sql);
		// query.list();

		Session session = null;
		try {
			session = getSF().openSession();
			session.beginTransaction();

			for (MsgInbox msg : msgs) {
				session.delete(msg);
			}
			session.getTransaction().commit();
		} finally {
			session.close();
		}
		// getSF().getCurrentSession().getTransaction().commit();
		// getSF().getCurrentSession().close();
	}
}
